package cn.xiongxf.userdetails;

import cn.xiongxf.domain.Login;
import cn.xiongxf.domain.Permission;
import cn.xiongxf.mapper.PermissionMapper;
import cn.xiongxf.service.ILoginService;
import cn.xiongxf.service.IPermissionService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class SKCCUserDetailService implements UserDetailsService {
    @Autowired
    private ILoginService loginService;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1.查询用户
        Login login = loginService.selectByUsername(username);
        if (login == null) throw new UsernameNotFoundException("用户名不存在");

        // 2.查询用户权限
        List<Permission> permissions = permissionMapper.selectByLoginId(login.getId());

        // 3.用户权限   List<Permission> -> List<GrantedAuthority>
        List<SimpleGrantedAuthority> authorities = permissions.stream().map(permission -> {
            log.info("用户登陆，加载用户权限：{}", permission.getSn());
            return new SimpleGrantedAuthority(permission.getSn());
        }).collect(Collectors.toList());
//        List<SimpleGrantedAuthority> authorities = permissions.stream()
//                .map(permission -> new SimpleGrantedAuthority(permission.getSn()))
//                .collect(Collectors.toList());

        // 登陆ID和用户名封装
        Login login2Token = new Login();
        login2Token.setId(login.getId());
        login2Token.setUsername(login.getUsername());

        // 4.返回用户详情
        return new User(
                // 用户
                JSON.toJSONString(login2Token),
                // 密码
                login.getPassword(),
                // 账户的4个状态
                login.getEnabled(),
                login.getAccountNonExpired(),
                login.getCredentialsNonExpired(),
                login.getAccountNonLocked(),
                // 权限
                authorities
        );
    }

}
